package com.mmall.controller;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Order;
import com.mmall.pojo.User;
import com.mmall.service.OrderService;
import com.mmall.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("order/")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @RequestMapping(value = "create.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse create(Order order, String loginToken){
        ServerResponse response = userService.userIsLogin(loginToken);
        if (!response.isSuccess()) {
            return response;
        }
        User user = (User) response.getData();
        order.setUserId(user.getId());
        order.setOrderNo(String.valueOf(new Date().getTime())+user.getId());
        return orderService.create(order);
    }

    @RequestMapping(value = "find.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse find(Integer id){
        return orderService.find(id);
    }

    @RequestMapping(value = "closeOrder.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse closeOrder(Order order){
        order.setStatus(Const.ORDER_STATUS_CLOSE);//订单状态
        order.setCloseTime(new Date());
        return orderService.updateOrder(order);
    }

    @RequestMapping(value = "pay.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse pay(Order order){
        order.setStatus(Const.ORDER_STATUS_CLOSE);//订单状态
        order.setPayStatus(Const.PAY_STATUS_YES);
        order.setPaymentType(Const.PAY_TYPE_ONLINE);
        order.setPaymentTime(new Date());
        return orderService.payMonet(order);
    }

    @RequestMapping(value = "delete.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse delete(Integer orderId){
        return orderService.deleteOrder(orderId);
    }

    @RequestMapping(value = "findDetail.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse findDetail(Integer orderId){
        return orderService.find(orderId);
    }

    @RequestMapping(value = "findMyOrderList.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse findMyOrderList(String loginToken){
        ServerResponse response = userService.userIsLogin(loginToken);
        if (!response.isSuccess()) {
            return response;
        }
        User user = (User) response.getData();
        return orderService.findMyOrderList(user.getId());
    }
}
